package chen.yi.component.xss.filter;

import chen.yi.component.xss.constant.WhiteConstant;
import chen.yi.component.xss.wrapper.CachedXssRequestWrapper;
import cn.hutool.core.util.StrUtil;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author huat
 **/
public class XssFilter implements Filter {
    private final List<String> whiteList=new ArrayList<String>();
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        String initParameter = filterConfig.getInitParameter(WhiteConstant.WHITE_KEY);
        if(StrUtil.isNotBlank(initParameter)){
            String[] whiteUrl = initParameter.split(",");
            whiteList.addAll(Arrays.asList(whiteUrl));
        }
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        // 双重包装：先缓存 → 后清理
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        String servletPath = httpRequest.getServletPath();
        if(whiteList.contains(servletPath)){
            chain.doFilter(request, response);
            return;
        }
        CachedXssRequestWrapper wrappedRequest = new CachedXssRequestWrapper(httpRequest);
        chain.doFilter(wrappedRequest, response);
    }
}
